package com.jagochan.module.springai.controller;

import com.jagochan.module.springai.common.ChatTypeConstants;
import com.jagochan.module.springai.common.repository.ChatHistoryRepository;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

@RequiredArgsConstructor
@RequestMapping("/ai")
@RestController
public class ChatController {

    private final ChatClient chatClient;
    private final ChatHistoryRepository chatHistoryRepository;

    @ApiOperation(value = "聊天")
    @RequestMapping(value = "/chat", produces = "text/html;charset=utf-8")
    public Flux<String> chatStream(@ApiParam("提示词") String prompt, @ApiParam("聊天ID") String chatId) {
        // 保存聊天ID
        chatHistoryRepository.save(ChatTypeConstants.CHAT, chatId);
        // 请求模型
        return chatClient.prompt()
                .user(prompt)
                .advisors(advisorSpec -> advisorSpec.param(AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY, chatId))
                .stream() // 流式输出
                .content();
    }

    /**
     * 阻塞式输出
     */
    @GetMapping("/chat/call")
    public String chat(String message) {
        return chatClient
                .prompt()
                .user(message)
                .call() // 阻塞
                .content();
    }

}
